import * as React from 'react';
import { observer } from 'mobx-react';
import { Upload, Icon, Modal, message } from 'antd';
import { IMAGE_UPLOAD_URL } from '../../service/Config';
import { getToken } from '../../service/Auth';
import { TOKEN_KEY } from '../../service/Config';

interface ImageUploaderProps {
    limit?: number;
    fileList: any[];
    onChange(fileList: any[]);
    onUpdate(fileList: any[]);
}

export class ImageUploader extends React.Component<ImageUploaderProps, any> {

    constructor(props) {
        super(props);

        this.state = {
            previewVisible: false,
            previewImage: '',
            fileList: []
        };
    }

    handleCancel = () => {
        this.setState({ previewVisible: false });
    };

    handlePreview = (file) => {
        this.setState({
            previewImage: file.url || file.thumbUrl,
            previewVisible: true,
        });
    }

    handleChange = (event) => {
        this.props.onChange(event.fileList);

        let status = event.file.status;
        if (status === 'done' || status === 'removed') {
            this.props.onUpdate(event.fileList.map(file => file.response));
        }
    }

    handleBeforeUpload = (file) => {
        let isImage = file.type.indexOf('image/') === 0;
        let isTooLarge = file.size > 1024 * 1024;
        if (!isImage) {
            message.error('只能上传图片格式的文件！');
        }
        if (isTooLarge) {
            message.error('只能上传1M大小的图片!');
        }
        return isImage && !isTooLarge;
    }

    render() {
        const { previewVisible, previewImage} = this.state;
        const limit = this.props.limit || 1;
        const headers = { [TOKEN_KEY]: getToken() };
        const uploadButton = <div>
            <Icon type="plus" />
            <div className="ant-upload-text">上传图片</div>
        </div>;
        const fileList = this.props.fileList || [];

        return (
            <div className="clearfix">
                <Upload
                    action={IMAGE_UPLOAD_URL}
                    listType="picture-card"
                    fileList={fileList}
                    onPreview={this.handlePreview}
                    onChange={this.handleChange}
                    beforeUpload={this.handleBeforeUpload}
                    headers={headers}
                >
                    {fileList.length >= limit ? null : uploadButton}
                </Upload>
                <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                    <img style={{ width: '100%' }} src={previewImage} />
                </Modal>
            </div>
        );
    }
}
